import os
import yaml
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import aiohttp
import asyncio
from .logConfig import setup_logging

# 配置日志记录
logger = setup_logging(__name__, os.path.join('logs', 'notify'))


# 加载配置文件
def load_config():
    config_path = os.path.join('config', 'notify_config.yml')
    with open(config_path, 'r', encoding='utf-8') as f:
        return yaml.safe_load(f)


# 异步发送邮件通知
async def send_email(subject, message, to_email):
    config = load_config()
    email_config = config.get('email', {})

    msg = MIMEMultipart()
    msg['From'] = email_config.get('from_email')
    msg['To'] = to_email
    msg['Subject'] = subject

    msg.attach(MIMEText(message, 'plain'))

    try:
        loop = asyncio.get_event_loop()
        await loop.run_in_executor(None, lambda: smtplib.SMTP(email_config.get('smtp_server'),
                                                              email_config.get('smtp_port')).starttls().login(
            email_config.get('smtp_username'), email_config.get('smtp_password')).sendmail(
            email_config.get('from_email'), msg['To'], msg.as_string()))
        logger.info(f"Email to {to_email} sent successfully!")
    except Exception as e:
        logger.error(f"Failed to {to_email} send email: {e}")


# 异步发送 WXpusher 通知
async def send_wxpusher_by_uids(subject, message, uids):
    config = load_config()
    wxpusher_config = config.get('wxpusher', {})

    url = "https://wxpusher.zjiecode.com/api/send/message"
    headers = {
        "Content-Type": "application/json"
    }
    payload = {
        "appToken": wxpusher_config.get('app_token'),
        "content": message,
        "summary": subject,
        "uids": uids
    }

    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(url, json=payload, headers=headers) as response:
                if response.status == 200:
                    logger.info(f"WXpusher message sent to {str(uids)} successfully!")
                else:
                    logger.error(f"Failed to send WXpusher message: {await response.text()}")
    except Exception as e:
        logger.error(f"Failed to send to {str(uids)} WXpusher message: {e}")


# 根据主题发送 WXpusher 通知
async def send_wxpusher_by_topic(subject, message, topic_ids):
    config = load_config()
    wxpusher_config = config.get('wxpusher', {})

    url = "https://wxpusher.zjiecode.com/api/send/message"
    headers = {
        "Content-Type": "application/json"
    }
    payload = {
        "appToken": wxpusher_config.get('app_token'),
        "content": message,
        "summary": subject,
        "topicIds": topic_ids
    }
    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(url, json=payload, headers=headers) as response:
                if response.status == 200:
                    logger.info(f"WXpusher message sent to {str(topic_ids)} successfully by topic!")
                else:
                    logger.error(f"Failed to send WXpusher message by topic: {await response.text()}")
    except Exception as e:
        logger.error(f"Failed to send to {str(topic_ids)} WXpusher message : {e}")


def _send_notification(taskConfigName: str, subject: str, html_message: str) -> None:
    '''

    :param taskConfigName: 任务通知的配置键名 （从config/notify_config.yml中读取）
    :param subject:   消息主题名称
    :param html_message: 消息内容，html格式
    :return:
    '''
    try:
        config = load_config()
        config_name = config.get(taskConfigName, {})

        if not config_name.get('enabled', False):
            logger.info(f"{taskConfigName} is not enabled.")
            return None
        message = html_message
        notify_methods = config_name.get('notify_method')
        if isinstance(notify_methods, str):
            notify_methods = [notify_methods]

        for method in notify_methods:
            if method == 'wxpusher':
                uids = config_name.get('wxpusher_uids', [])
                topic_ids = config_name.get('wxpusher_topic_ids', [])
                if uids or topic_ids:
                    import asyncio
                    if uids:
                        asyncio.run(send_wxpusher_by_uids(subject, message, uids))
                        logger.info(f"{config_name}:WXpusher message sent successfully to uid:{str(uids)}!")
                    if topic_ids:
                        asyncio.run(send_wxpusher_by_topic(subject, message, topic_ids))
                        logger.info(f"{config_name}:WXpusher message sent successfully to topic:{str(topic_ids)}!")
            elif method == 'email':
                recipients = config_name.get('email_recipients', [])
                if recipients:
                    import asyncio
                    for recipient in recipients:
                        asyncio.run(send_email(subject, message, recipient))
                    logger.info(f"{config_name}:Email sent successfully to {recipients}!")
    except Exception as e:
        logger.error(f"Failed to send {config_name}: {e}")
